<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions(chartData = {}) {
      this.chart.setOption({
        title: {
          text: chartData.text,
          left: "center",
          top: 10,
          textStyle: {
            color: "#fff",
            fontSize: "16",
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        // legend: {
        //   left: 'center',
        //   bottom: '10',
        //   data: chartData.name,
        // },
        series: [
          {
            name: chartData.text,
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '38%'],
            data: [
              {
                name: chartData.name[0],
                value: chartData.value[0],
              },
              {
                name: chartData.name[1],
                value: chartData.value[1],
              },
              {
                name: chartData.name[2],
                value: chartData.value[2],
              },
              {
                name: chartData.name[3],
                value: chartData.value[3],
              },
              {
                name: chartData.name[4],
                value: chartData.value[4],
              },
              {
                name: chartData.name[5],
                value: chartData.value[5],
              },
              {
                name: chartData.name[6],
                value: chartData.value[6],
              }
            ],
            // 修饰饼形图文字相关的样式 label对象
            label: {
              fontSize: 10
            },
            // 修饰引导线样式
            labelLine: {
              // 连接到图形的线长度
              length: 10,
              // 连接到文字的线长度
              length2: 10
            },
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
